//
//  WNPickerVC.swift
//  WalkNovel
//
//  Created by Kevin on 2023/8/15.
//

import UIKit

class WNPickerVC: WNBaseVC {
    
    lazy var cancelBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.tag = 0
        btn.setTitle("Cancel", for: .normal)
        btn.setTitleColor(.init(named: "gray_666666"), for: .normal)
        btn.titleLabel?.font = .wn_font(name: .bold, size: 16)
        btn.addTarget(self, action: #selector(wn_touchBtn(sender:)), for: .touchUpInside)
        return btn
    }()
    
    lazy var sureBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.tag = 1
        btn.setTitle("Done", for: .normal)
        btn.setTitleColor(.init(named: "red_FE95B4"), for: .normal)
        btn.titleLabel?.font = .wn_font(name: .bold, size: 16)
        btn.addTarget(self, action: #selector(wn_touchBtn(sender:)), for: .touchUpInside)
        return btn
    }()
    
    lazy var pickerView: UIPickerView = {
        let view = UIPickerView()
        view.backgroundColor = .clear
        view.delegate = self
        view.dataSource = self
        return view
    }()
    // pickerView有几列
    var components = 0
    
    var seleteSex : Int = 0
    
    var pickerType: PickerType = .none
    
    // 性别
    var sexArray = ["Male", "Female", "Secrecy"]
    
    // birthday
    var currentDateArr: (String, String, String) = {
        return (Date().wn_year(), Date().wn_mmonth(), Date().wn_day())
    }()
    
    var yearArray: [String] = {
        var arr = [String]()
        for i in (wn_toInt(Date().wn_year())-100)...wn_toInt(Date().wn_year()) {
            arr.append("\(i)")
        }
        return arr
    }()
    
    var monthArray: [String] = {
        var arr = [String]()
        for i in 1...12 {
            if i < 10 {
                arr.append("0\(i)")
            }else {
                arr.append("\(i)")
            }
        }
        return arr
    }()
    
    var dayArray: [String] = {
        var arr = [String]()
        for i in 1...31 {
            if i < 10 {
                arr.append("0\(i)")
            }else {
                arr.append("\(i)")
            }
        }
        return arr
    }()
    
    // 选中的数据
    var select = ("", "", "")
    
    var isCurrentYear = false
    
    var isCurrentMonth = false
    
    var finshClosure: StringClosure?
    
    var resultStr = String()
    
    convenience init(_ type: PickerType, _ counts: Int, _ str: String = "") {
        self.init()
        pickerType = type
        components = counts
        switch pickerType {
        case .birthday:
            if str == "" {
                pickerView.selectRow(100, inComponent: 0, animated: true)
                pickerView.selectRow(wn_toInt(Date().wn_mmonth()) - 1, inComponent: 1, animated: true)
                pickerView.selectRow(wn_toInt(Date().wn_day()) - 1, inComponent: 2, animated: true)
                select = (Date().wn_year(), Date().wn_mmonth(), Date().wn_day())
            }else {
                // str：2002-01-01
                let arr = str.components(separatedBy: "-")
                select = (arr[0], arr[1], arr[2])
                var year = (100-wn_toInt(Date().wn_year())+wn_toInt(arr[0]))
                if year < 0 {
                    year = 0
                }
                pickerView.selectRow(year, inComponent: 0, animated: true)
                pickerView.selectRow(wn_toInt(arr[1])-1, inComponent: 1, animated: true)
                pickerView.selectRow(wn_toInt(arr[2])-1, inComponent: 2, animated: true)
            }
        case .sex:
            if wn_toInt(str) == 0 {
                seleteSex = 2
            }else {
                seleteSex = wn_toInt(str)-1
            }
            pickerView.selectRow(seleteSex, inComponent: 0, animated: true)
            resultStr = "\(seleteSex)"
        case .none:
            break
        }
        pickerView.reloadAllComponents()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    override func viewConfig() {
        wn_hidNavView()
        view.addSubview(cancelBtn)
        view.addSubview(sureBtn)
        view.addSubview(pickerView)
        cancelBtn.snp.makeConstraints { (make) in
            make.top.equalTo(10)
            make.left.equalTo(16)
        }
        sureBtn.snp.makeConstraints { (make) in
            make.top.equalTo(10)
            make.right.equalTo(-16)
        }
        pickerView.snp.makeConstraints { (make) in
            make.top.equalTo(40)
            make.left.equalTo(49)
            make.right.equalTo(-49)
            make.bottom.equalTo(0)
        }
        view.wn_cornerCustom([.topLeft, .topRight], 20)
    }
    
    @objc func wn_touchBtn(sender: UIButton) {
        switch sender.tag {
        case 0:
            finshClosure?("Cancel")
        default:
            if components == 3 {
                resultStr = select.0 + "-" + select.1 + "-" + select.2
            }
            if pickerType == .birthday {
                finshClosure?(resultStr)
            }else {
                // 设置性别会走到这
                finshClosure?(resultStr)
            }
        }
    }
}

//MARK: - PickerViewDelegate, UIPickerViewDataSource
extension WNPickerVC: UIPickerViewDelegate, UIPickerViewDataSource {
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return components
    }
    
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        switch pickerType {
        case .birthday:
            switch component {
            case 0: return yearArray.count
            case 1: return isCurrentYear ? Int(currentDateArr.1)! : monthArray.count
            default: return isCurrentMonth ? Int(currentDateArr.2)! : dayArray.count
            }
        case .sex:
            return sexArray.count
        case .none:
            return 0
        }
    }
    
    func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
        return 35
    }
    
    func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {
        return (ScreenW-98)/CGFloat(components)
    }
    
    func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
        for v in pickerView.subviews where v.frame.size.height < 1 {
            v.backgroundColor = .white
        }
        let label = UILabel()
        label.textColor = .init(named: "black_222222")
        label.textAlignment = .center
        label.font = .wn_font(name: .bold, size: 16)
        label.text = self.pickerView(pickerView, titleForRow: row, forComponent: component)
        return label
    }
    
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        switch pickerType {
        case .birthday:
            switch component {
            case 0: return yearArray[row]
            case 1: return monthArray[row]
            default: return dayArray[row]
            }
        case .sex:
            return sexArray[row]
        case .none:
            return nil
        }
    }
    
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        switch pickerType {
        case .birthday:
            switch component {
            case 0:
                isCurrentYear = (yearArray[row] == currentDateArr.0)
                select.0 = yearArray[row]
            case 1:
                isCurrentMonth = isCurrentYear && (monthArray[row] == currentDateArr.1)
                dayArray = judgeDays(Int(select.0)!, row+1)
                pickerView.reloadComponent(2)
                pickerView.selectRow(0, inComponent: 2, animated: true)
                select.1 = monthArray[row]
                select.2 = dayArray[0]
            default:
                select.2 = dayArray[row]
            }
        case .sex:
            if row == 2 {
                resultStr = "0"
            }else {
                resultStr = "\(row+1)"
            }
        case .none:
            break
        }
    }
    
    func judgeDays(_ year: Int, _ month: Int) -> [String] {
        if month == 2 {
            var arr = [String]()
            var day : Int = 28
            if(year%4 == 0 && year%100 != 0) || year%400 == 0 {
                day = 29
            }
            for i in 1...day {
                if i < 10 {
                    arr.append("0\(i)")
                }else {
                    arr.append("\(i)")
                }
            }
            return arr
        }else if month == 4 || month == 6 || month == 9 || month == 11 {
            var arr = [String]()
            for i in 1...30 {
                if i < 10 {
                    arr.append("0\(i)")
                }else {
                    arr.append("\(i)")
                }
            }
            return arr
        }else {
            var arr = [String]()
            for i in 1...31 {
                if i < 10 {
                    arr.append("0\(i)")
                }else {
                    arr.append("\(i)")
                }
            }
            return arr
        }
    }
}
